import React from 'react';
import { Button, Form, Input, List, Avatar, DatePicker, Divider, Modal, Radio, message } from 'antd';
import BreadcrumbCustom from '../common/BreadcrumbCustom';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
import fetchRequest from '../../fetch/fetchRequest';
import Utils from '../common/Utils'

// 图片导入
import img1 from './../../style/img/github.png';
import img2 from './../../style/img/heart.png';
import img3 from './../../style/img/mail.png';
import img4 from './../../style/img/0.png';
import img5 from './../../style/img/sun.png';

const { TextArea } = Input;

const imgArr = [img1, img2, img3, img4, img5]

class Memorandum extends React.Component {
    state = {
        visible: false,
        data: []
    };

    componentWillMount() {
        this.getMemorandums()
    }
    // 获取备忘录列表
    getMemorandums() {
        fetchRequest.fetchR('memorandums', 'get')
            .then(res => {
                if (res.error === undefined) {
                    this.setState({
                        data: res,
                    })
                }
            }).catch(err => {
                message.error('数据获取失败!');
            })
    }
    // 打开添加的弹框
    showModal = () => {
        this.setState({ visible: true, isEdit: false });
    }
    handleCancel = () => {
        this.setState({ visible: false });
    }
    handleCreate = () => {
        const { isEdit, editId } = this.state;
        const form = this.props.form;
        if (isEdit) { //修改一个备忘录
            this.handleEdit(editId)
        } else { // 添加一个备忘录
            form.validateFields((err, values) => {
                if (err) {
                    return;
                }

                fetchRequest.fetchR('memorandum', 'post', values)
                    .then(res => {
                        if (res.error === undefined) {
                            this.getMemorandums()
                            message.success('添加成功')
                        }
                    }).catch(err => {
                        message.error('添加失败!');
                    })

                form.resetFields();
                this.setState({ visible: false });
            });
        }
    }

    // 删除备忘录
    handleDelete = (id) => {
        fetchRequest.fetchR(`memorandum/${id}`, 'delete')
            .then(res => {
                message.success('删除成功')
                this.getMemorandums()
            }).catch(err => {
                message.error('删除失败!');
            })
    }

    // 打开修改的弹框
    showEditModal = (id) => {
        // 获取对应修改的备忘录的id
        fetchRequest.fetchR(`memorandum/${id}`, 'get')
            .then(res => {
                this.setState({
                    editMemorandumData: res,
                    isEdit: true,
                    visible: true,
                    editId: id,
                })
            }).catch(err => {
                message.error('数据获取失败!');
            })
    }
    // 修改备忘录
    handleEdit = (id) => {
        const form = this.props.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            fetchRequest.fetchR(`memorandum/${id}`, 'put', values)
                .then(res => {
                    message.success('修改成功')
                    this.getMemorandums()
                }).catch(err => {
                    message.error('修改失败!');
                })

            form.resetFields();
            this.setState({ visible: false });
        });
    }

    render() {
        const { visible, data, isEdit, editMemorandumData } = this.state;
        const { getFieldDecorator } = this.props.form;
        moment.locale('zh-cn');
        // 格式化时间
        const format = "YYYY-MM-DD HH:mm:ss";
        return (
            <div>
                <BreadcrumbCustom paths={['首页', '备忘录']} />
                <div className='formBody'>
                    <Button type='primary' onClick={this.showModal}>添加备忘录</Button>
                    <Divider />
                    <List
                        itemLayout="vertical"
                        pagination={{
                            onChange: (page) => {
                                console.log(page);
                            },
                        }}
                        dataSource={data}
                        renderItem={item => (
                            <List.Item
                                key={item.title}
                                actions={[<a onClick={() => this.showEditModal(item.id)}>修改</a>, <a onClick={() => this.handleDelete(item.id)}>删除</a>]}>
                                <List.Item.Meta
                                    avatar={<Avatar src={imgArr[item.img]} />}
                                    title={item.title}
                                    description={Utils.formateDate(item.time)}
                                />
                                {item.content}
                            </List.Item>
                        )}
                    />
                    <Modal
                        visible={visible}
                        title="添加备忘录"
                        okText="确定"
                        cancelText="取消"
                        onCancel={this.handleCancel}
                        onOk={this.handleCreate}
                    >
                        <Form layout="vertical">
                            <Form.Item label="标题">
                                {getFieldDecorator('title', {
                                    rules: [{ required: true, message: '请输入标题' }],
                                    initialValue: isEdit ? editMemorandumData.title : ''
                                })(
                                    <Input />
                                )}
                            </Form.Item>
                            <Form.Item label="时间">
                                {getFieldDecorator('time', {
                                    rules: [{ required: true, message: '请选择时间' }],
                                    initialValue: isEdit ? moment(Utils.formateDate(editMemorandumData.time), format) : ''
                                })(
                                    <DatePicker showTime format={format} locale={locale} />
                                )}
                            </Form.Item>
                            <Form.Item label="图片">
                                {getFieldDecorator('img', {
                                    rules: [{ required: true, message: '请选择图片' }],
                                    initialValue: isEdit ? editMemorandumData.img : ''
                                })(
                                    <Radio.Group>
                                        <Radio value="0"><img src={img1} style={{ width: 50, height: 50 }} alt="图片"/></Radio>
                                        <Radio value="1"><img src={img2} style={{ width: 50, height: 50 }} alt="图片"/></Radio>
                                        <Radio value="2"><img src={img3} style={{ width: 50, height: 50 }} alt="图片"/></Radio>
                                        <Radio value="3"><img src={img4} style={{ width: 50, height: 50 }} alt="图片"/></Radio>
                                        <Radio value="4"><img src={img5} style={{ width: 50, height: 50 }} alt="图片"/></Radio>
                                    </Radio.Group>
                                )}
                            </Form.Item>
                            <Form.Item label="内容">
                                {getFieldDecorator('content', {
                                    rules: [{ required: true, message: '请输入内容' }],
                                    initialValue: isEdit ? editMemorandumData.content : ''
                                })(
                                    <TextArea rows={10} />
                                )}
                            </Form.Item>
                        </Form>
                    </Modal>
                </div>
            </div>
        )
    }
}

export default Form.create()(Memorandum)